﻿using System;
using System.Web;
using System.Drawing.Imaging;
using System.IO;
using System.Web.UI.WebControls;
using OF.Common;
using System.Configuration;

namespace OF.Common
{
    /// <summary>
    /// 项目名称：红包中国积分商城系统
    /// 功能简述：通用上传类
    /// 作   者: YWJ  
    /// 创建时间：2012-06-26
    /// 文件说明：实现网站通用上传的调用，已经上传目录的设置 
    /// </summary>
    public class UploadCommon
    {
        #region 变量初始化设置

        //图片上传路径
        private string webFilePath = "";

        //上传目录
        private string _picdir = "";

        //返回图片地址
        private string strpic = string.Empty;

        //获取站点信息
        private string sitename = "xiaguanzi";

        //获取上传的大小限制
        private string strpiclimitsize = ConfigurationManager.AppSettings["PicLimitSize"];

        //获取 年 月 信息
        private string year; //= DateTime.Now.Year.ToString();
        private string month; // = DateTime.Now.Month.ToString();

        //设置父目录
        private string updir1;

        //上传文件类型  默认 为0 图片上传
        private int _uploadtype = 0;

        private string returnstr = string.Empty;

        #endregion

        #region 设置子目录

        private string updir2 = string.Empty;

        #endregion

        #region  构造函数

        public UploadCommon()
        {
            sitename = "xiaguanzi";
            updir1 = "/upload/" + sitename;
            year = DateTime.Now.Year.ToString();
            month = DateTime.Now.Month.ToString();
            updir1 = "/upload/" + sitename;
        }

        #endregion

        #region 大 中 小 图高宽设置

        private int _bx = 0;
        private int _by = 0;

        private int _nx = 0;
        private int _ny = 0;

        private int _sx = 0;
        private int _sy = 0;

        //缩略图生成模式
        private string _mode = "";

        #endregion

        #region 预设缩略图 高度 宽度 上传的模式

        private string[,] confstr = new string[3, 8]
            {
                //bx    by     nx    ny   sx   sy  mode  _picdir
                {"260", "260", "160", "160", "60", "60", "A", "pic"},
                {"260", "260", "120", "120", "60", "60", "A", ""},
                {"0", "0", "0", "0", "0", "0", "", ""}
            };

        #endregion

        #region 格式化配置文件

        private void FormatConfigstr(int t)
        {
            _bx = _bx == 0 ? Convert.ToInt32(confstr[t, 0]) : _bx;
            _by = _by == 0 ? Convert.ToInt32(confstr[t, 1]) : _by;
            _nx = _nx == 0 ? Convert.ToInt32(confstr[t, 2]) : _nx;
            _ny = _ny == 0 ? Convert.ToInt32(confstr[t, 3]) : _ny;
            _sx = _sx == 0 ? Convert.ToInt32(confstr[t, 4]) : _sx;
            _sy = _sy == 0 ? Convert.ToInt32(confstr[t, 5]) : _sy;
            _mode = _mode == "" ? Convert.ToString(confstr[t, 6]) : _mode;
            _picdir = _picdir == "" ? Convert.ToString(confstr[t, 7]) : _picdir;

            //判断是否设置上传路径如果没有设置 去除 一个 /
            if (_picdir != "")
            {
                updir2 = "/" + _picdir + "/" + year + "/" + month + "/".ToString().Trim();
            }
            else
            {
                updir2 = "/" + year + "/" + month + "/".ToString().Trim();
            }

        }

        #endregion

        #region 设置变量

        public int bx
        {
            set { _bx = value; }
            get { return _bx; }
        }

        public int nx
        {
            set { _nx = value; }
            get { return _nx; }
        }

        public int sx
        {
            set { _sx = value; }
            get { return _sx; }
        }

        public int by
        {
            set { _by = value; }
            get { return _by; }
        }

        public int ny
        {
            set { _ny = value; }
            get { return _ny; }
        }

        public int sy
        {
            set { _sy = value; }
            get { return _sy; }
        }

        public string picdir
        {
            set { _picdir = value; }
            get { return _picdir; }
        }

        public string mode
        {
            set { _mode = value; }
            get { return _mode; }
        }

        public int uploadtype
        {
            set { _uploadtype = value; }
            get { return _uploadtype; }
        }

        public string setuploadtype
        {
            set { sitename = value; }
            get { return sitename; }
        }

        #endregion 设置变量

        #region 判断是否为图片格式

        public Boolean ispic(string fileContentType)
        {
            if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/jpeg" ||
                fileContentType == "image/png" || fileContentType == "image/pjpeg" || fileContentType == "image/x-png")
            {
                return true;
            }
            return false;
        }

        #endregion

        #region 根据post数据流上传图片

        /// <summary>
        /// post上传图片的方法
        /// </summary>
        /// <param name="hpf">数据流</param>
        /// <param name="t">内置模式0-（260，160，60）1-（260，120，60） 2其它自主情况</param>
        /// <returns></returns>
        public string UpImageFromHpFile(HttpPostedFile hpf, int t)
        {
            string returnstr = null;
            if (hpf.ContentLength != 0)
            {
                //获取文件类型
                string fileContentType = hpf.ContentType;
                //获取文件上传后的名称
                //生成不重复的随机数
                System.Guid guid = new Guid();
                guid = Guid.NewGuid();
                string strGuid = guid.ToString("N");

                string imgName = string.Empty;

                //当前文件扩展名
                string extendname = System.IO.Path.GetExtension(hpf.FileName).Trim();

                string upextentname = ConfigurationManager.AppSettings["UploadPicType"];
                string[] Arrayextend = upextentname.Split('|');
                bool safeExtendFile = false;
                foreach (string indextendname in Arrayextend)
                {
                    if (indextendname == extendname)
                    {
                        safeExtendFile = true;
                        break;
                    }
                }
                if (safeExtendFile == true)
                {
                    imgName = strGuid + extendname; //上传后的文件名称
                    FormatConfigstr(t); //初始化配置文件
                    webFilePath = HttpContext.Current.Server.MapPath(updir1 + "/" + updir2 + imgName);
                    string webDirPath = HttpContext.Current.Server.MapPath(updir1 + updir2);

                    //根据设定的上传文件类型判断是否保存文件
                    if (_uploadtype == 0 && ispic(fileContentType))
                    {

                        //目录是否存在，不存在建立
                        if (!Directory.Exists(webDirPath))
                        {
                            System.IO.Directory.CreateDirectory(webDirPath);
                        }
                        //保存上传文件
                        if (!File.Exists(webFilePath))
                        {
                            try
                            {
                                Stream fs = hpf.InputStream;
                                byte[] by = new byte[hpf.InputStream.Length];
                                using (FileStream fStream = new FileStream(webFilePath, FileMode.Create))
                                {
                                    int oszie = fs.Read(by, 0, by.Length);
                                    while (oszie > 0)
                                    {
                                        if (oszie > 0)
                                        {
                                            fStream.Write(by, 0, by.Length);
                                        }
                                        oszie = fs.Read(by, 0, by.Length);
                                    }
                                }


                                returnstr = updir1 + updir2 + imgName;
                            }
                            catch (Exception ex)
                            {
                                ex.StackTrace.ToString();

                                return null;
                            }

                            string webFilePathB = "b";
                            string webFilePathN = "n";
                            string webFilePathS = "s";
                            //判断大中小图片上传
                            if (_bx != 0)
                            {
                                createThumbsForSize(webFilePath, updir1, updir2, webFilePathB, imgName);
                            }
                            if (_nx != 0)
                            {
                                createThumbsForSize(webFilePath, updir1, updir2, webFilePathN, imgName);
                            }
                            if (_sx != 0)
                            {
                                createThumbsForSize(webFilePath, updir1, updir2, webFilePathS, imgName);
                            }

                        }

                    }

                }
                else
                {
                    return null;
                }


            }
            else
            {
                return null;
            }
            //hpf.ContentType
            return returnstr;
        }

        #endregion

        #region 根据图片大中小生成图片

        /// <summary>
        /// 生成各种尺寸的图片
        /// </summary>
        /// <param name="webFilePath">原文件路径</param>
        /// <param name="up1">路径前半部分</param>
        /// <param name="up2">路径后半部分</param>
        /// <param name="upPathType">b,n,s三种参数</param>
        /// <param name="upname">文件名</param>
        private void createThumbsForSize(string webFilePath, string up1, string up2, string upPathType, string upname)
        {
            string webfilePathThumbs = HttpContext.Current.Server.MapPath(up1 + "/" + upPathType + "/" + up2 + upname);
            string webFolderPath = HttpContext.Current.Server.MapPath(up1 + "/" + upPathType + "/" + up2);
            if (!Directory.Exists(webFolderPath))
            {
                System.IO.Directory.CreateDirectory(webFolderPath);
            }
            MakeThumbnail(webFilePath, webfilePathThumbs, _bx, _by, mode);
        }

        #endregion

        #region 根据模式生成缩略图

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="fileupload">上传的控件ID</param> 
        /// <param name="fileupload">内置模式 1- （260，160,60 等比压缩三种缩略图） </param> 
        /// <param name="fileupload">内置模式 2- （260，120,60 等比压缩三种缩略图） </param> 

        public string MakeThumbnailByMode(FileUpload fileupload, int t)
        {
            //返回值设置
            string returnstr = null;

            // 检查上传控件中是否包含文件
            if (fileupload.HasFile)
            {
                //获取文件类型
                string fileContentType = fileupload.PostedFile.ContentType;
                //获取文件上传后名称
                //生成不重复的随机数
                System.Guid guid = new Guid();
                guid = Guid.NewGuid();
                string strGuid = guid.ToString("N");


                //上传的文件名称
                string imgName = string.Empty;

                //文件扩展名
                string extendname = System.IO.Path.GetExtension(fileupload.PostedFile.FileName).Trim();


                //开始配置可上传的文件后缀名
                string upextendname = ".jpg|.gif|.png|.bmp|.jpeg|.swf";
                string[] Arrayextend = upextendname.Split('|');

                //检查上传的文件后缀名是否在配置文件中
                foreach (string inextendname in Arrayextend)
                {
                    #region 后缀验证通过
                    if (inextendname.Trim().Equals(extendname.ToLower()))
                    {
                        #region 判断大小 超过了就不予上传 by ywj 2012-08-31
                        int piclimitsize = 1024000;
                        try
                        {
                            piclimitsize = Convert.ToInt32(strpiclimitsize);
                        }
                        catch (Exception ex)
                        {
                            piclimitsize = 1024000;
                        }
                        // 开始判断文件大小
                        if (fileupload.PostedFile.InputStream.Length > piclimitsize)
                        {

                            returnstr = "ERROR01"; //上传文件大小超过限制
                            return returnstr;
                        }
                        #endregion

                        #region 开始上传
                        imgName = strGuid + extendname; //产生上传后文件名称
                        FormatConfigstr(t); //初始化配置文件

                        //设置上传目录
                        //updir2 = "/" + _picdir + "/" + year + "/" + month + "/".ToString().Trim();//多余
                        webFilePath = HttpContext.Current.Server.MapPath(updir1 + "/" + updir2 + imgName);

                        string webDirPath = HttpContext.Current.Server.MapPath(updir1 + updir2);

                        System.IO.BinaryReader reader = new System.IO.BinaryReader(fileupload.PostedFile.InputStream);
                        //设置FireFox 文件类型判断

                        //根据设定的上传文件类型判断是否保存文件
                        if (_uploadtype == 0 && ispic(fileContentType) &&
                            CheckUploadImgExtension(fileupload.PostedFile, reader, extendname.ToLower()))
                        {

                            //判断目录是否存在，不存在建立
                            if (!Directory.Exists(webDirPath))
                            {
                                System.IO.Directory.CreateDirectory(webDirPath);
                            }
                            //保存上传的文件
                            if (!File.Exists(webFilePath))
                            {
                                try
                                {
                                    fileupload.SaveAs(webFilePath);
                                    returnstr = updir1 + updir2 + imgName;
                                }
                                catch (Exception ex)
                                {
                                    ex.StackTrace.ToString();

                                    returnstr = "ERROR02"; //图片保存失败
                                    return returnstr;
                                }
                            }

                            #region 生成缩略图
                            //设置大图 中图 小图的目录
                            string webFilePathsb = string.Empty;
                            string webFilePathsn = string.Empty;
                            string webFilePathss = string.Empty;

                            //根据配置文件生成大图
                            if (_bx != 0)
                            {
                                //大图
                                webFilePathsb = HttpContext.Current.Server.MapPath(updir1 + "/b/" + updir2 + imgName);
                                string webDirPathsb = HttpContext.Current.Server.MapPath(updir1 + "/b/" + updir2);
                                //目录不存在建立目录
                                if (!Directory.Exists(webDirPathsb))
                                {
                                    System.IO.Directory.CreateDirectory(webDirPathsb);
                                }
                                //调用生成缩略图方法
                                MakeThumbnail(webFilePath, webFilePathsb, _bx, _by, mode);
                            }
                            //根据配置文件生成中图
                            if (_nx != 0)
                            {
                                //中图上传
                                webFilePathsn = HttpContext.Current.Server.MapPath(updir1 + "/n/" + updir2 + imgName);
                                string webDirPathsn = HttpContext.Current.Server.MapPath(updir1 + "/n/" + updir2);
                                //目录不存在建立目录
                                if (!Directory.Exists(webDirPathsn))
                                {
                                    System.IO.Directory.CreateDirectory(webDirPathsn);
                                }
                                //调用生成缩略图方法
                                MakeThumbnail(webFilePath, webFilePathsn, _nx, _ny, mode);
                            }
                            //根据配置文件生成小图
                            if (_sx != 0)
                            {
                                //小图上传
                                webFilePathss = HttpContext.Current.Server.MapPath(updir1 + "/s/" + updir2 + imgName);
                                string webDirPathss = HttpContext.Current.Server.MapPath(updir1 + "/s/" + updir2);
                                //目录不存在建立目录
                                if (!Directory.Exists(webDirPathss))
                                {
                                    System.IO.Directory.CreateDirectory(webDirPathss);
                                }
                                //调用生成缩略图方法
                                MakeThumbnail(webFilePath, webFilePathss, _sx, _sy, mode);
                            }
                            #endregion
                        }
                        #endregion

                        //设置为图片上传，但是上传的不是图片文件
                        else if (_uploadtype == 0)
                        {

                            returnstr = "ERROR03"; // 图片格式有误
                            return returnstr;
                        }
                        else
                        {

                            #region 设置了其他上传类型限制只进行保存操作
                            //判断目录是否存在，不存在建立
                            if (!Directory.Exists(webDirPath))
                            {
                                System.IO.Directory.CreateDirectory(webDirPath);
                            }
                            //保存上传的文件
                            if (!File.Exists(webFilePath))
                            {
                                try
                                {
                                    fileupload.SaveAs(webFilePath);
                                    returnstr = updir1 + updir2 + imgName;
                                }
                                catch (Exception ex)
                                {
                                    ex.StackTrace.ToString();

                                    returnstr = "ERROR04"; //文件保存失败
                                    return returnstr;
                                }
                            }
                            #endregion
                        }
                        break;
                    }
                }
                if (returnstr == null)
                {
                    returnstr = "ERROR06";
                }

                return returnstr;
            }
                    #endregion

            else
            {

                returnstr = "ERROR05";
                return returnstr;
            }
        }

        #endregion

        #region 上传附件

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="fileupload">上传的控件ID</param> 

        public string UploadFile(FileUpload fileupload, int t)
        {
            //返回值设置
            string returnstr = null;

            #region 检查上传控件中是否包含文件

            if (fileupload.HasFile)
            {
                //获取文件类型
                string fileContentType = fileupload.PostedFile.ContentType;

                string imgName = fileupload.FileName;//fileupload.PostedFile.FileName;
                string filename = Path.GetFileNameWithoutExtension(imgName);//不包含扩展名的文件名
                imgName = filename+"-"+DateTime.Now.ToString("yyyyMMddHHmmss");
                //文件扩展名
                string extendname = System.IO.Path.GetExtension(fileupload.PostedFile.FileName).Trim();
                imgName = imgName + extendname;

                //开始配置可上传的文件后缀名
                string upextendname = ConfigurationManager.AppSettings["UploadFileType"]; //".pdf|.rar|.txt|.ppt|.doc|.docx|.xls|.xlsx|pptx";
                string[] Arrayextend = upextendname.Split('|');

                //检查上传的文件后缀名是否在配置文件中
                foreach (string inextendname in Arrayextend)
                {
                    if (inextendname.Trim().Equals(extendname.ToLower()))
                    {
                        #region 判断大小 超过了就不予上传 by ywj 2012-08-31
                        int piclimitsize = 1024000;
                        try
                        {
                            piclimitsize = Convert.ToInt32(strpiclimitsize);
                        }
                        catch (Exception ex)
                        {
                            piclimitsize = 1024000;
                        }
                        // 开始判断文件大小
                        if (fileupload.PostedFile.InputStream.Length > piclimitsize)
                        {

                            returnstr = "ERROR01"; //上传文件大小超过限制
                            return returnstr;
                        }
                        #endregion

                        //设置上传目录
                        updir2 = "/attachment/" + year + "/" + month + "/".ToString().Trim();
                        webFilePath = HttpContext.Current.Server.MapPath(updir1 + "/" + updir2 + imgName);

                        string webDirPath = HttpContext.Current.Server.MapPath(updir1 + updir2);

                        System.IO.BinaryReader reader = new System.IO.BinaryReader(fileupload.PostedFile.InputStream);

                        //根据设定的上传文件类型判断是否保存文件   上传附件的类型暂未验证
                        if (_uploadtype == 0)
                        {
                            //判断目录是否存在，不存在建立
                            if (!Directory.Exists(webDirPath))
                            {
                                System.IO.Directory.CreateDirectory(webDirPath);
                            }
                            //保存上传的文件
                            if (!File.Exists(webFilePath))
                            {
                                try
                                {
                                    fileupload.SaveAs(webFilePath);
                                    returnstr = updir1 + updir2 + imgName;
                                }
                                catch (Exception ex)
                                {
                                    returnstr = "ERROR02"; //图片保存失败
                                    return returnstr;
                                }
                            }//文件名重复
                            else
                            {
                                returnstr = "ERROR09"; //文件名重复 
                                return returnstr;
                            }
                        }
                        //设置为图片上传，但是上传的不是图片文件
                        else if (_uploadtype == 0)
                        {
                            returnstr = "ERROR03"; // 图片格式有误
                            return returnstr;
                        }
                        else
                        {
                            #region 默认上传
                            //设置了其他上传类型限制只进行保存操作
                            //判断目录是否存在，不存在建立
                            if (!Directory.Exists(webDirPath))
                            {
                                System.IO.Directory.CreateDirectory(webDirPath);
                            }
                            //保存上传的文件
                            if (!File.Exists(webFilePath))
                            {
                                try
                                {
                                    fileupload.SaveAs(webFilePath);
                                    returnstr = updir1 + updir2 + imgName;
                                }
                                catch (Exception ex)
                                {
                                    ex.StackTrace.ToString();

                                    returnstr = "ERROR04"; //文件保存失败
                                    return returnstr;
                                }
                            }
                            else
                            {
                                returnstr = "ERROR09"; //文件名重复 
                                return returnstr;
                            }
                            #endregion
                        }
                        break;
                    }
                }
                if (returnstr == null)
                {
                    returnstr = "ERROR06";
                }

                return returnstr;
            }
            #endregion
            else
            {
                returnstr = "ERROR05"; //没有文件
                return returnstr;
            }
        }

        #endregion

        #region 下载附件
        public string DownloadFile(HttpResponse Response, string webDirPath)
        {
            string ext = System.IO.Path.GetExtension(webDirPath).Trim();
            if (!File.Exists(webDirPath))
            {
                return "该文件已经不存在";
            }

            FileInfo info = new FileInfo(webDirPath);
            long fileSize = info.Length;
            Response.Clear();
            Response.ContentType = "application/x-zip-compressed";
            string strTemp = System.Web.HttpUtility.UrlEncode(info.Name, System.Text.Encoding.UTF8);//解决文件名乱码
            Response.AddHeader("Content-Disposition", "attachment;filename=" + strTemp);
            //不指明Content-Length用Flush的话不会显示下载进度 
            Response.AddHeader("Content-Length", fileSize.ToString());
            Response.TransmitFile(webDirPath, 0, fileSize);
            Response.Flush();
            Response.Close();
            return null;
        }
        #endregion

        #region 生成缩略图

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param> 
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height,
                                         string mode)
        {
            try
            {
                System.Drawing.Image.FromFile(originalImagePath);
            }
            catch (Exception ex)
            {
                //判断是否为图片 by ywj 20120830
                return;
            }

            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW": //指定高宽缩放（可能变形） 
                    break;
                case "W": //指定宽，高按比例 
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H": //指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut": //指定高宽裁减（不变形） 
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                case "A": //图片等比缩放
                    if (originalImage.Width / originalImage.Height >= width / height)
                    {
                        if (originalImage.Width > width)
                        {
                            towidth = width;
                            toheight = (originalImage.Height * width) / originalImage.Width;
                            if (toheight == 0)
                            {
                                toheight = 1;
                            }
                        }
                        else
                        {
                            towidth = originalImage.Width;
                            toheight = originalImage.Height;
                        }
                    }
                    else
                    {
                        if (originalImage.Height > height)
                        {
                            toheight = height;
                            towidth = (originalImage.Width * height) / originalImage.Height;
                            if (towidth == 0)
                            {
                                towidth = 1;
                            }
                        }
                        else
                        {
                            towidth = originalImage.Width;
                            toheight = originalImage.Height;
                        }
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //白色填充
            g.Clear(System.Drawing.Color.White);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                        new System.Drawing.Rectangle(x, y, ow, oh),
                        System.Drawing.GraphicsUnit.Pixel);


            //控制保存图片的质量相关参数
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1);

            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 100L);
            myEncoderParameters.Param[0] = myEncoderParameter;

            ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, jgpEncoder, myEncoderParameters);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        #endregion

        #region 取图像编码格式

        /// <summary>
        /// 取图像编码格式
        /// </summary>
        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }

        #endregion

        #region 通过原始图片的地址 根据参数取得 各种模式图片地址

        /// <summary>
        /// picaddress-原始图片地址(完整)
        /// pictype-需要获取图片的模式 s---小图
        ///                           n---中图
        ///                           b---大图
        /// </summary>
        public string getOtherTypeThumbnail(string picaddress, string pictype)
        {
            string returnpicaddress = null;

            int start = -1;
            int sitenamelength = 0;
            string picaddrfront = string.Empty;

            #region 如果是子站对接主站的商品获取各种图片地址

            if (picaddress == null || picaddress == "")
            {
                return "";
            }
            if (picaddress.IndexOf("/hongbao/") > -1)
            {
                start = picaddress.IndexOf("/hongbao/");
                sitenamelength = ("/hongbao/").Length;
                picaddrfront = picaddress.Substring(0, start);
                if (pictype.Trim() == "b" || pictype.Trim() == "n" || pictype.Trim() == "s")
                {
                    pictype = pictype + "/";
                    returnpicaddress = picaddress.Insert(start + sitenamelength, pictype);
                    return returnpicaddress;
                }
            }

            #endregion

            if (picaddress == null || picaddress == "")
            {
                return returnpicaddress;
            }
            start = picaddress.IndexOf("/" + sitename + "/");
            sitenamelength = ("/" + sitename + "/").Length;
            if (start <= 0)
            {
                return returnpicaddress;
            }
            picaddrfront = picaddress.Substring(0, start);

            if (pictype.Trim() == "b" || pictype.Trim() == "n" || pictype.Trim() == "s")
            {
                pictype = pictype + "/";
                returnpicaddress = picaddress.Insert(start + sitenamelength, pictype);
            }

            return returnpicaddress;
        }

        #endregion

        #region 给出提示

        public string MessageShow(string strreturn)
        {
            string str = strreturn;

            string strshow = "上传成功";

            if (str == "ERROR01")
            {
                strshow = "图片大小超过限制";
            }
            else if (str == "ERROR02")
            {
                strshow = "图片保存失败";
            }
            else if (str == "ERROR03")
            {
                strshow = "图片格式有误";
            }
            else if (str == "ERROR04")
            {
                strshow = "文件保存失败";
            }
            else if (str == "ERROR05")
            {
                strshow = "没有选择文件";
            }
            else if (str == "ERROR06")
            {
                strshow = "不是允许的上传文件格式";
            }
            else if (str == null)
            {
                strshow = "上传失败";
            }
            else
            {
                strshow = "上传成功";
            }
            return strshow;
        }

        #endregion

        #region 根据文件名判断文件扩展名 和 根据流真正判断文件类型的关键函数

        /// <summary>
        /// 根据文件名判断文件扩展名 和 根据流真正判断文件类型的关键函数
        /// </summary>
        /// <param name="thefile">上传的文件</param>
        /// <returns>true - 允许上传的文件类型 false-不允许</returns>
        public static bool CheckUploadImgExtension(System.Web.HttpPostedFile thefile, System.IO.BinaryReader reader,
                                                   string fileExtension)
        {
            ////取得文件的扩展名,并转换成小写
            //string fileExtension = System.IO.Path.GetExtension(thefile.FileName).ToLower();

            //限定只能上传jpg和gif图片
            string[] allowExtension = { ".jpg", ".gif", ".bmp", ".png", ".bmp", ".jpeg" };

            bool fileOk = false;
            //对上传的文件的类型进行一个个匹对
            for (int i = 0; i < allowExtension.Length; i++)
            {
                if (fileExtension == allowExtension[i])
                {

                    fileOk = true;

                    //System.IO.BinaryReader reader = new System.IO.BinaryReader(thefile.InputStream);
                    string fileclass = "";
                    byte buffer;
                    try
                    {
                        buffer = reader.ReadByte();
                        fileclass = buffer.ToString();
                        buffer = reader.ReadByte();
                        fileclass += buffer.ToString();
                    }
                    catch
                    {
                        fileOk = false;
                    }

                    //reader.Close();

                    //说明 255216 是jpg; 7173 是gif; 6677 是BMP, 13780是PNG; 7790 是exe, 8297 是rar
                    if (fileclass == "255216" || fileclass == "7173" || fileclass == "6677" || fileclass == "13780")
                    {
                        fileOk = true;
                    }
                    else
                    {
                        fileOk = false;
                    }

                    break;
                }
            }

            return fileOk;
        }

        #endregion
    }
}